<?php

namespace App\Http\Middleware\Auth;

use App\Http\Services\LoginService;
use App\Models\Member;
use App\Models\Minilogin;
use Closure;

class MiniappLogin
{
    /**
     * 小程序登录验证
     */
    public function handle($request, Closure $next)
    {
        $token = $request->header('token');

        if (empty($token)) {
            return response([
                'code' => 401,
                'msg' => '权限不足',
                'data' => []
            ], 401);
        }

        $login = new LoginService();
        $adminId = $login->authcode($token, 'DECODE');

        if (empty($adminId)) {
            return response([
                'code' => 401,
                'msg' => '无效的Token',
                'data' => []
            ], 401);
        }

        // 模拟用户登录
        $minilogin = Minilogin::where(['uid' => $adminId])->first();
        if ($minilogin && isset($minilogin['df_uid'])) {
            $adminId = $minilogin['df_uid'];
            define("IS_VISUAL", 1);//模拟账号
        }

        $request->offsetSet('wechat_admin_id', $adminId);
        if ($adminId) {
            define("UID", $adminId);
        }

        //记录用户最后访问时间
        Member::where("id", "=", $adminId)->update(['last_login_time' => time(), 'last_login_ip' => request()->ip()]);
        $res = $this->_valid_account($adminId);
        if ($res) {
            return response($res);
        }

        return $next($request);
    }

    /**
     * 判断条件
     * @Author   thomashtao               bosslen
     * @DateTime 2022-04-26T15:34:31+0800
     * @param    [type]                   $uid    [description]
     */
    private function _valid_account($uid = NULL)
    {
        if (!$uid) return "";
        $member = Member::where("id", "=", $uid)->first();
        if (!$member) return "";

        if (is_str_has($member['username'], "'")) {
            Member::where("id", "=", $member['id'])->update([
                'username' => str_replace("'", '', $member['username'])
            ]);
        }

        $route = app('request')->route();
        if (!$route) return "";
        $action = $route->getAction();
        $controller = '@';
        if (isset($action['controller'])) {
            $controller = class_basename($action['controller']);
        }
        list($routeControllerName, $routeActionName) = explode('@', $controller);
        $routeControllerName = strtolower(str_replace("Controller", "", $routeControllerName));

        /*if ($routeActionName != 'quick_profile') {
            $checkFields = ["avatar", "gender", "height", "birthday"];
            //检查是否填写基本信息
            $flag = false;
            foreach ($checkFields as $k => $v) {
                if (empty($checkFields[$v]) || ($v == 'gender' && $member[$v] == 'U')) {
                    $flag = true;
                }
            }
            if ($flag) {
                return [
                    "code" => 411,
                    "data" => [
                        'url' => "member/info/edit_quick",
//                    "errmsg" => "请先完善基本信息"
                    ]
                ];
            }
        }*/

        $ca = strtolower($routeControllerName . '/' . $routeActionName);
        if ($member['cancel'] == 0 && $ca != 'member/recover') {
            return [
                "code" => 411,
                "data" => [
                    'url' => "member/recover",
                    "errmsg" => "你的账户已注销"
                ]
            ];
        }

        if ($member['is_forbidden'] != 1 && $ca != 'member/ban') {
            return [
                "code" => 411,
                "data" => [
                    'url' => "public/forbidden",
                    "errmsg" => "你的账户已禁止登陆"
                ]
            ];
        }
    }
}
